package com.css.fxfzaqbz.modules.base.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.css.fxfzaqbz.base.response.RestResponse;
import com.css.fxfzaqbz.base.upload.entity.AttachmentInfoEntity;
import com.css.fxfzaqbz.base.upload.service.AttachmentInfoService;
import com.css.fxfzaqbz.modules.base.entity.*;
import com.css.fxfzaqbz.modules.base.queryParams.SeismicQueryParam;
import com.css.fxfzaqbz.modules.base.repository.BuildingVulnerabilityRepository;
import com.css.fxfzaqbz.modules.base.repository.CountProcessRepository;
import com.css.fxfzaqbz.modules.base.service.HypergraphService;
import com.css.fxfzaqbz.modules.base.service.SeismicResultService;
import com.css.fxfzaqbz.modules.base.service.SeismicService;
import com.css.fxfzaqbz.modules.data.repository.DistrictBoundaryRepository;
import com.css.fxfzaqbz.modules.maps.vo.MapViewVO;
import com.css.fxfzaqbz.modules.maps.service.MapManagerService;
import com.css.fxfzaqbz.modules.supergraph.entity.*;
import com.css.fxfzaqbz.modules.supergraph.repository.OrgDivisionRepository;
import com.css.fxfzaqbz.modules.supergraph.service.SupergraphService;
import com.css.fxfzaqbz.modules.supergraph.vo.ResponseVO;
import com.css.fxfzaqbz.modules.supergraph.vo.TjVO;
import com.css.fxfzaqbz.util.*;
import com.css.fxfzaqbz.zcpt.sys.service.SysAreaService;
import lombok.extern.slf4j.Slf4j;
import org.slw.common.helper.PropsHelper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URLDecoder;
import java.util.*;
import java.util.stream.Collectors;
@Slf4j
@Service
public class SeismicServiceImpl implements SeismicService {
    @Resource
    BuildingVulnerabilityRepository buildingVulnerabilityRepository;
    @Resource
    CountProcessRepository countProcessRepository;
    @Resource
    SeismicResultService seismicResultService;
    @Resource
    private RestTemplateUtil restTemplateUtil;

    @Resource
    private AttachmentInfoService attachmentInfoService;


    @Value("${image.localDir}")
    private String localDir;

    @Resource
    private DownloadsFile downloadsFile;

    @Resource
    private MapManagerService mapManagerService;

    @Resource
    OrgDivisionRepository orgDivisionRepository;
    @Resource
    DistrictBoundaryRepository districtBoundaryRepository;
    @Resource
    HypergraphService hypergraphService;
    @Resource
    RedisTemplate<String, String> redisTemplate;
    @Resource
    SysAreaService sysAreaService;
    @Resource
    SupergraphService supergraphService;
    @Resource
    RestTemplate restTemplate;

    @Override
    public RestResponse countSeismic(SeismicQueryParam param) throws InterruptedException {
        RestResponse restResponse = null;
        //确保各个省市区下建筑物易损性数据完整
        for (District district : param.getList()) {
            List<BuildingVulnerability> vulnerabilityList = buildingVulnerabilityRepository.getByDistrict(district);
            if (vulnerabilityList.size() != 300) {
                log.error("请确保" + district.getProvince() + "," + district.getCity() + "," +
                        district.getPrefecture() + "下建筑物易损性矩阵数据完整");
                return RestResponse.fail("请确保" + district.getProvince() + "," + district.getCity() + "," +
                        district.getPrefecture() + "下建筑物易损性矩阵数据完整");
            }
            for (BuildingVulnerability buildingVulnerability : vulnerabilityList) {
                if (!"1".equals(buildingVulnerability.getIsNull())) {
                    log.error("请确保" + district.getProvince() + "," + district.getCity() + "," +
                            district.getPrefecture() + "下建筑物易损性矩阵数据完整");
                    return RestResponse.fail("请确保" + buildingVulnerability.getProvince() + "," + buildingVulnerability.getCity() + "," +
                            buildingVulnerability.getPrefecture() + "下建筑物易损性矩阵数据完整");
                }
            }
        }
        ArrayList<SeismicResult> seismicResults = new ArrayList<>();
        for (District district : param.getList()) {
            //根据省市区查询基础数据5张表
            Properties configGroup = PropsHelper.loadProps("slw-config.properties");
            String url = configGroup.getProperty("restTemplateUrl") + "/datacenter/house/getHouseData";
            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("province", district.getProvince());
            paramMap.put("city", district.getCity());
            paramMap.put("county", district.getPrefecture());
            paramMap.put("czzzDataVersion",param.getCzzzDataVersion());
            paramMap.put("czfzzDataVersion",param.getCzfzzDataVersion());
            paramMap.put("nczzdlzzDataVersion",param.getNczzdlzzDataVersion());
            paramMap.put("nczzjtzzDataVersion",param.getNczzjtzzDataVersion());
            paramMap.put("ncfzzDataVersion",param.getNcfzzDataVersion());
            ResponseEntity<String> cchResponseEntity = restTemplateUtil.sendPostHttpRequest1(url, paramMap);
            List<HouseData> houses = JSONObject.parseArray(cchResponseEntity.getBody(), HouseData.class);
            if (houses.size()==0){
                return RestResponse.fail("数据版本下没有房屋数据");
            }
            ArrayList<HouseData> data = new ArrayList<>();
            BigDecimal sumArea = BigDecimal.ZERO;
            Map<String, List<HouseData>> listMap = houses.stream().collect(Collectors.groupingBy(HouseData::getJglx));
            for (Map.Entry<String, List<HouseData>> entry : listMap.entrySet()) {
                String key = entry.getKey();
                Map<String, List<HouseData>> map = entry.getValue().stream().collect(Collectors.groupingBy(HouseData::getMqsfld));
                for (Map.Entry<String, List<HouseData>> listEntry : map.entrySet()) {
                    String key1 = listEntry.getKey();
                    List<HouseData> value = listEntry.getValue();
                    BigDecimal zero = BigDecimal.ZERO;
                    for (HouseData houseData : value) {
                        zero = zero.add(houseData.getDcmj());
                        sumArea = sumArea.add(houseData.getDcmj());
                    }
                    HouseData houseData1 = new HouseData();
                    houseData1.setJglx(key);
                    houseData1.setMqsfld(key1);
                    houseData1.setZdcmj(zero);
                    data.add(houseData1);
                }
            }
            for (int i = 0; i < 10; i++) {
                List<String> list = Arrays.asList("6度", "7度", "8度", "9度", "未设防", "无设防信息");
                for (String s : list) {
                    List<BuildingVulnerability> vulnerability = buildingVulnerabilityRepository.getVulnerability(district.getProvince(), district.getCity(), district.getPrefecture(), i + "", s, param.getLieDu());
                    CountProcess countProcess = new CountProcess();
                    countProcess.setId(UUIDGenerator.getUUID());
                    countProcess.setProvince(district.getProvince());
                    countProcess.setCity(district.getCity());
                    countProcess.setPrefecture(district.getPrefecture());
                    countProcess.setStructureType(vulnerability.get(0).getStructureType());
                    countProcess.setIntensity(s);
                    countProcess.setOne(vulnerability.get(4).getX());
                    countProcess.setTwo(vulnerability.get(3).getX());
                    countProcess.setThree(vulnerability.get(2).getX());
                    countProcess.setFour(vulnerability.get(1).getX());
                    countProcess.setFive(vulnerability.get(0).getX());
                    BigDecimal zero = BigDecimal.ZERO;
                    countProcess.setRatio(zero);
                    for (HouseData item : data) {
                        if ((i + "").equals(item.getJglx()) && s.equals(item.getMqsfld())) {
                            countProcess.setRatio(item.getZdcmj());
                        }
                    }
                    countProcessRepository.save(countProcess);
                }
            }
            CountProcess countProcess = new CountProcess();
            countProcess.setProvince(district.getProvince());
            countProcess.setCity(district.getCity());
            countProcess.setPrefecture(district.getPrefecture());
            BigDecimal a = new BigDecimal("1.0");
            BigDecimal b = new BigDecimal("0.8");
            BigDecimal c = new BigDecimal("0.5");
            BigDecimal d = new BigDecimal("0.3");
            BigDecimal e = new BigDecimal("0.0");
            BigDecimal res = BigDecimal.ZERO;
            List<CountProcess> countProcessList = countProcessRepository.query(countProcess);
            for (CountProcess process : countProcessList) {
                BigDecimal sum = BigDecimal.ZERO;
                sum = sum.add(process.getOne().multiply(a).setScale(5));
                sum = sum.add(process.getTwo().multiply(b).setScale(5));
                sum = sum.add(process.getThree().multiply(c).setScale(5));
                sum = sum.add(process.getFour().multiply(d).setScale(5));
                res = res.add(sum.multiply(process.getRatio()));
            }
            BigDecimal result = res.divide(sumArea, 3, RoundingMode.HALF_UP);
            //清空过程表
            countProcessRepository.delete();
            //保存结果
            seismicResultService.save(param, district, result);
            SeismicResult seismicResult = new SeismicResult();
            seismicResult.setProvince(district.getProvince());
            seismicResult.setCity(district.getCity());
            seismicResult.setPrefecture(district.getPrefecture());
            seismicResult.setRes(result);
            seismicResults.add(seismicResult);
        }

        Properties configGroup = PropsHelper.loadProps("slw-config.properties");
        String url = configGroup.getProperty("supergraphRestTemplateUrl");
        List<District> list = param.getList();
        List<String> codes=new ArrayList<>();
        for (District district : list) {
            String district1=null;
            //北京市，上海市，天津市，重庆市
            if ("北京市".equals(district.getProvince())||"上海市".equals(district.getProvince())||"天津市".equals(district.getProvince())||"重庆市".equals(district.getProvince())){
                district1=district.getCity()+"-"+district.getPrefecture();
            }else {
                district1=district.getProvince()+"-"+district.getCity()+"-"+district.getPrefecture();
            }
            String code = orgDivisionRepository.getCodeByTaskDistrict(district1);
            codes.add(code);
        }

//        List<String> strings = list.stream().map(District::getPrefecture).collect(Collectors.toList());
        String extent = districtBoundaryRepository.getExtent(codes);
        String center = districtBoundaryRepository.getcenter(codes);
        String[] split = extent.substring(4, extent.length() - 1).split(",");
        String[] s1 = split[0].split(" ");
        String[] s2 = split[1].split(" ");
        String leftX = s1[0];
        String leftY = s1[1];
        String rightX = s2[0];
        String rightY = s2[1];
        int level = getLevel(Double.valueOf(leftX), Double.valueOf(leftY), Double.valueOf(rightX), Double.valueOf(rightY));
        String[] s = center.substring(6, center.length() - 1).split(" ");
        String centerX = s[0];
        String centerY = s[1];

        //图例
        List<String> strings1 = Arrays.asList("sys_seismic_result@fxfzaqbz.1@@sys_seismic_result@fxfzaqbz");
        Layerr layerr1 = new Layerr(url + "/map-fxfzaqbz/rest/maps/sys_seismic_result@fxfzaqbz", strings1);

        List<String> strings15 = Arrays.asList("district_boundary_province@fxfzypg@@district_boundary_china@fxfzypg","district_boundary_city@fxfzypg@@district_boundary_china@fxfzypg","district_boundary_county@fxfzypg@@district_boundary_china@fxfzypg","district_boundary_province_text@fxfzypg@@district_boundary_china@fxfzypg","district_boundary_city_text@fxfzypg@@district_boundary_china@fxfzypg","district_boundary_county_text@fxfzypg@@district_boundary_china@fxfzypg");
        Layerr layerr15 = new Layerr(url + "/map-fxfzypg/rest/maps/district_boundary_china@fxfzypg",strings15);
        List<Layerr> layerrs = Arrays.asList(layerr15,layerr1);

        //图层
        String url1 = url + "/map-fxfzaqbz/rest/maps/sys_seismic_result@fxfzaqbz";
        Layer layer1 = new Layer("TILE","抗震能力风险初步评估分区图",url1);

        String url15 = url + "/map-fxfzypg/rest/maps/district_boundary_china@fxfzypg";
        Layer layer15 = new Layer("TILE","中国行政区划图", url15);
        List<Layer> layers = Arrays.asList(layer15,layer1);

        //获取Web打印出图模板列表
        List<TemplateEntity> templateEntityList = hypergraphService.getWebprintingLayoutsList();

        //根据参数设置请求体
        String jsonString = supergraphService.getRequestVOJsonStringByTjmb(param.getTjmb(),templateEntityList,param.getTjbt(),param.getZtdw(),layerrs,layers,Double.valueOf(centerX),Double.valueOf(centerY),Double.valueOf(leftX),Double.valueOf(leftY),Double.valueOf(rightX),Double.valueOf(rightY),level,false);
        Map map = JSONObject.parseObject(jsonString, Map.class);
        //获取超图服务token
                String token = hypergraphService.getToken();
        if (PlatformObjectUtils.isEmpty(token)){
            log.error("缺少超图服务token");
            return RestResponse.fail("缺少超图服务token");
        }
        String urll = url+ "/webprinting/rest/webprinting/v1/jobs.json?token="+token;
//        Map map1 = JSONObject.parseObject(Plot.getJsonString(), Map.class);
        ResponseEntity<String> stringResponseEntity = restTemplateUtil.sendPostHttpRequest2(urll, map);
        String body = stringResponseEntity.getBody();
        List<ResponseVO> responseVO = JSON.parseArray(body, ResponseVO.class);
        String path = "";
        String imageId = "";
        String tjmb = param.getTjmb();
//        MapViewVO view = mapManagerService.view(tjmb);
//        String type = view.getType();
        Map<String, Object> responseMap = new HashMap<>();
        if (responseVO != null || responseVO.size() > 0) {
            path = responseVO.get(0).getPath() + "/" + "result";
            //    String dateDir = new SimpleDateFormat("/yyyy/MM/dd").format(new Date());
            String savePath = localDir;
            path = path.replace("@", "%40");
            System.out.println("路径  " + path);
            String path2 = responseVO.get(0).getPath() + ".rjson";
            Map<String, Object> map2 = new HashMap<>();
            boolean flag = true;
            while (flag) {
                ResponseEntity<String> responseEntity = restTemplateUtil.sendHttpRequest3(path2, map2);
                String body1 = responseEntity.getBody();
                String[] split1 = body1.split("status");
                if (split1[1].contains("ERROR")){
                    log.error("超图服务打印失败");
                    return RestResponse.fail("超图服务打印失败");
                }
                if (split1[1].contains("FINISHED")){
                    flag = false;
                    continue;
                }
                Thread.sleep(500);
            }
            restResponse = downloadsFile.downloadByUrl(path, savePath);
            imageId = restResponse.getData().toString();
            AttachmentInfoEntity attach = attachmentInfoService.getAttach(imageId);
            responseMap.put("attach", attach);
            responseMap.put("count", "房屋抗震能力评估");
            responseMap.put("title", "");
        }
        File file = new File(localDir);
        File[] files = file.listFiles();
        for (File file1 : files) {
            if (file1.isFile()) {
                file1.delete();
            }
        }


        restResponse = RestResponse.succeed(responseMap);

        return restResponse;
    }

    @Override
    public RestResponse houseDestory(SeismicQueryParam param) throws UnsupportedEncodingException, InterruptedException {
        RestResponse restResponse = null;
        //确保各个省市区下建筑物易损性数据完整
        for (District district : param.getList()) {
            List<BuildingVulnerability> vulnerabilityList = buildingVulnerabilityRepository.getByDistrict(district);
            if (vulnerabilityList.size() != 300) {
                log.error("请确保" + district.getProvince() + "," + district.getCity() + "," +
                        district.getPrefecture() + "下建筑物易损性矩阵数据完整");
                return RestResponse.fail("请确保" + district.getProvince() + "," + district.getCity() + "," +
                        district.getPrefecture() + "下建筑物易损性矩阵数据完整");
            }
            for (BuildingVulnerability buildingVulnerability : vulnerabilityList) {
                if (!"1".equals(buildingVulnerability.getIsNull())) {
                    log.error("请确保" + buildingVulnerability.getProvince() + "," + buildingVulnerability.getCity() + "," +
                            buildingVulnerability.getPrefecture() + "下建筑物易损性矩阵数据完整");
                    return RestResponse.fail("请确保" + buildingVulnerability.getProvince() + "," + buildingVulnerability.getCity() + "," +
                            buildingVulnerability.getPrefecture() + "下建筑物易损性矩阵数据完整");
                }
            }


        }
        String uuid = UUIDGenerator.getUUID();
        for (District district : param.getList()) {
            countProcessRepository.deleteHouseDestory(district, param.getIaId());
            //根据省市区查询基础数据5张表
            Properties configGroup = PropsHelper.loadProps("slw-config.properties");
            String url = configGroup.getProperty("restTemplateUrl") + "/datacenter/house/getHouseData";
            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("province", district.getProvince());
            paramMap.put("city", district.getCity());
            paramMap.put("county", district.getPrefecture());
            paramMap.put("czzzDataVersion", param.getCzzzDataVersion());
            paramMap.put("czfzzDataVersion", param.getCzfzzDataVersion());
            paramMap.put("nczzdlzzDataVersion", param.getNczzdlzzDataVersion());
            paramMap.put("nczzjtzzDataVersion", param.getNczzjtzzDataVersion());
            paramMap.put("ncfzzDataVersion", param.getNcfzzDataVersion());
            ResponseEntity<String> cchResponseEntity = restTemplateUtil.sendPostHttpRequest1(url, paramMap);
            List<HouseData> houses = JSONObject.parseArray(cchResponseEntity.getBody(), HouseData.class);
            if (houses.size()==0){
                return RestResponse.fail("数据版本下没有房屋数据");
            }

            List<HouseDestoryEntity> houseDestoryEntitieList = new ArrayList<>();

            for (HouseData house : houses) {
                List<BuildingVulnerability> vulnerability = buildingVulnerabilityRepository.getVulnerability(district.getProvince(), district.getCity(), district.getPrefecture(), house.getJglx(), house.getMqsfld(), param.getLieDu());
                vulnerability = vulnerability.stream().sorted(Comparator.comparing(BuildingVulnerability::getX).reversed()).collect(Collectors.toList());
//                String destroy = vulnerability.get(0).getDestroy();
                // BuildingVulnerability buildingVulnerability = vulnerability.stream().max(Comparator.comparing(BuildingVulnerability::getX)).get();
                HouseDestoryEntity houseDestoryEntity = new HouseDestoryEntity();
                houseDestoryEntity.setProvince(district.getProvince());
                houseDestoryEntity.setCity(district.getCity());
                houseDestoryEntity.setCounty(district.getPrefecture());
                houseDestoryEntity.setJglx(house.getJglx());
                houseDestoryEntity.setMqsfld(house.getMqsfld());
                houseDestoryEntity.setMaxDestoryType(vulnerability.get(0).getDestroy());
                houseDestoryEntity.setId(UUIDGenerator.getUUID());
                houseDestoryEntity.setIaId(param.getIaId());
                houseDestoryEntity.setGeom(house.getGeom());
                houseDestoryEntity.setJzmc(house.getJzmc());
                houseDestoryEntity.setBuildTime(house.getBuildTime());
                houseDestoryEntity.setLongitude(house.getLongitude());
                houseDestoryEntity.setLatitude(house.getLatitude());
                houseDestoryEntity.setResultAnalysis(uuid);
                houseDestoryEntitieList.add(houseDestoryEntity);
            }
            countProcessRepository.saveHouseDestory(houseDestoryEntitieList);
        }

        Properties configGroup = PropsHelper.loadProps("slw-config.properties");
        String url = configGroup.getProperty("supergraphRestTemplateUrl");
        List<District> list = param.getList();
        List<String> codes = new ArrayList<>();
        for (District district : list) {
            String district1 = null;
            //北京市，上海市，天津市，重庆市
            if ("北京市".equals(district.getProvince()) || "上海市".equals(district.getProvince()) || "天津市".equals(district.getProvince()) || "重庆市".equals(district.getProvince())) {
                district1 = district.getCity() + "-" + district.getPrefecture();
            } else {
                district1 = district.getProvince() + "-" + district.getCity() + "-" + district.getPrefecture();
            }
            String code = orgDivisionRepository.getCodeByTaskDistrict(district1);
            codes.add(code);
        }

//        List<String> strings = list.stream().map(District::getPrefecture).collect(Collectors.toList());
        String extent = districtBoundaryRepository.getExtent(codes);
        String center = districtBoundaryRepository.getcenter(codes);
        String[] split = extent.substring(4, extent.length() - 1).split(",");
        String[] s1 = split[0].split(" ");
        String[] s2 = split[1].split(" ");
        String leftX = s1[0];
        String leftY = s1[1];
        String rightX = s2[0];
        String rightY = s2[1];
        int level = getLevel(Double.valueOf(leftX), Double.valueOf(leftY), Double.valueOf(rightX), Double.valueOf(rightY));
        String[] s = center.substring(6, center.length() - 1).split(" ");
        String centerX = s[0];
        String centerY = s[1];


/*        //图例
        List<String> strings1 = Arrays.asList("sys_house_destory@fxfzaqbz.2@@sys_house_destory@fxfzaqbz");
        Layerr layerr1 = new Layerr(url + "/map-fxfzaqbz/rest/maps/sys_house_destory@fxfzaqbz", strings1);

        List<String> strings15 = Arrays.asList("district_boundary_province@fxfzypg@@district_boundary_china@fxfzypg","district_boundary_city@fxfzypg@@district_boundary_china@fxfzypg","district_boundary_county@fxfzypg@@district_boundary_china@fxfzypg","district_boundary_province_text@fxfzypg@@district_boundary_china@fxfzypg","district_boundary_city_text@fxfzypg@@district_boundary_china@fxfzypg","district_boundary_county_text@fxfzypg@@district_boundary_china@fxfzypg");
        Layerr layerr15 = new Layerr(url + "/map-fxfzypg/rest/maps/district_boundary_china@fxfzypg",strings15);
        List<Layerr> layerrs = Arrays.asList(layerr15,layerr1);*/
/*
        //图层
        String url1 = url + "/map-fxfzaqbz/rest/maps/sys_house_destory@fxfzaqbz";
        Layer layer1 = new Layer("TILE","房屋破坏分布图",url1);

        String url15 = url + "/map-fxfzypg/rest/maps/district_boundary_china@fxfzypg";
        Layer layer15 = new Layer("TILE","中国行政区划图", url15);
        List<Layer> layers = Arrays.asList(layer15,layer1);*/


        TjVO tjVO=new TjVO("房屋破坏分布图",param.getTjmb(),uuid,param.getTjbt(),"0");
        Map<String,String> tempLayerUrlMap = getTempLayerUrlMapByTjVO(tjVO);
        List<Layer> layers = getLayer(tjVO.getTjlx(),tempLayerUrlMap);
        List<Layerr> layerrs = getLayerrs(tjVO.getTjlx(),tempLayerUrlMap);




        //获取Web打印出图模板列表
        List<TemplateEntity> templateEntityList = hypergraphService.getWebprintingLayoutsList();

        //根据参数设置请求体
        String jsonString = supergraphService.getRequestVOJsonStringByTjmb(param.getTjmb(),templateEntityList,param.getTjbt(),param.getZtdw(),layerrs,layers,Double.valueOf(centerX),Double.valueOf(centerY),Double.valueOf(leftX),Double.valueOf(leftY),Double.valueOf(rightX),Double.valueOf(rightY),level,false);
        Map map = JSONObject.parseObject(jsonString, Map.class);
        //获取超图服务token
        //获取超图服务token
        String token = hypergraphService.getToken();
        if (PlatformObjectUtils.isEmpty(token)) {
            log.error("缺少超图服务token");
            return RestResponse.fail("缺少超图服务token");
        }
        String urll = url + "/webprinting/rest/webprinting/v1/jobs.json?token=" + token;
//        Map map1 = JSONObject.parseObject(Plot.getJsonString(), Map.class);
        ResponseEntity<String> stringResponseEntity = restTemplateUtil.sendPostHttpRequest2(urll, map);
        String body = stringResponseEntity.getBody();
        List<ResponseVO> responseVO = JSON.parseArray(body, ResponseVO.class);
        String path = "";
        String imageId = "";
        String tjmb = param.getTjmb();
        MapViewVO view = mapManagerService.view(tjmb);
        String type = view.getType();
        Map<String, Object> responseMap = new HashMap<>();
        if (responseVO != null || responseVO.size() > 0) {
            path = responseVO.get(0).getPath() + "/" + "result";
            //    String dateDir = new SimpleDateFormat("/yyyy/MM/dd").format(new Date());
            String savePath = localDir;
            path = path.replace("@", "%40");
            System.out.println("路径  " + path);
            String path2 = responseVO.get(0).getPath() + ".rjson";
            Map<String, Object> map2 = new HashMap<>();
            boolean flag = true;
            while (flag) {
                ResponseEntity<String> responseEntity = restTemplateUtil.sendHttpRequest3(path2, map2);
                String body1 = responseEntity.getBody();
                String[] split1 = body1.split("status");
                if (split1[1].contains("ERROR")){
                    log.error("超图服务打印失败");
                    return RestResponse.fail("超图服务打印失败");
                }
                if (split1[1].contains("FINISHED")){
                    flag = false;
                    continue;
                }
                Thread.sleep(500);
                System.out.println("图片正在打印...");
            }
            restResponse = downloadsFile.downloadByUrl(path, savePath);
            imageId = restResponse.getData().toString();
            AttachmentInfoEntity attach = attachmentInfoService.getAttach(imageId);
            responseMap.put("attach", attach);
            responseMap.put("count", "房屋破坏评估");
            responseMap.put("title", "");
            responseMap.put("sdaId", uuid);
        }
        File file = new File(localDir);
        File[] files = file.listFiles();
        for (File file1 : files) {
            if (file1.isFile()) {
                file1.delete();
            }
        }


        restResponse = RestResponse.succeed(responseMap);


        return restResponse;
    }

    private int getLevel(Double valueOf, Double valueOf1, Double valueOf2, Double valueOf3) {
        int level = 4;//默认级别4
        double minLon = valueOf;
        double minLat = valueOf1;
        double maxLon = valueOf2;
        double maxLat = valueOf3;
        //获取最大差值
        double diffLon = maxLon - minLon;
        double diffLat = maxLat - minLat;
        double diffMax = diffLon;
        if(diffLon < diffLat){
            diffMax = diffLat;
        }
//        int diff = Math.round(diffMax);
//        long round = Math.round(diffMax);
        int[] levelArr = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14};
        Double[] diffArr = {360.0,180.0,90.0,45.0,22.0,11.0,5.0,2.5,1.25, 0.6,0.3,0.15,0.07,0.03,0.0};
        for (int i = 0; i < diffArr.length; i++) {
            if (diffMax - diffArr[i] >= 0) {
                level = levelArr[i];
                break;
            }
        }

        return level;
    }



    //根据图件数据版本信息获取临时图层URL的Map
    public Map<String,String> getTempLayerUrlMapByTjVO(TjVO tjVO){
        Map<String,String> tempLayerUrlMap = new HashMap<>();
        String tjlx = tjVO.getTjlx();//图件类型
        String uuid = tjVO.getDataVersion();//数据版本
        String num = tjVO.getNum();//数据类型num
        if (PlatformObjectUtils.isNotEmpty(uuid) && PlatformObjectUtils.isNotEmpty(num)) {
            if ("房屋破坏分布图".equals(tjlx)) {
                String tempLayerUrl = getTempLayerUrlByDataType("sys_house_destory",uuid);
                tempLayerUrlMap.put("sys_house_destory",tempLayerUrl);
            }
        }
        return tempLayerUrlMap;
    }

    //根据表名、数据版本获取临时图层URL
    public String getTempLayerUrlByDataType(String tableName,String uuid){
        String tempLayerUrl = "";
        String layerUrl = "";
        String sqlText = "";
        Properties configGroup = PropsHelper.loadProps("slw-config.properties");
        String url = configGroup.getProperty("supergraphRestTemplateUrl");
        //一键出图
        if(tableName.equals("sys_house_destory")){//房屋破坏
            layerUrl = url + "/map-fxfzaqbz/rest/maps/sys_house_destory@fxfzaqbz";
            sqlText = "result_analysis='"+uuid+"' and del_flag='0'";
        }
        if (PlatformObjectUtils.isNotEmpty(layerUrl) && PlatformObjectUtils.isNotEmpty(sqlText)) {
            //获取临时图层
            tempLayerUrl = getSqlTempLayer(layerUrl, sqlText,true);
            System.out.println("临时图层----"+tempLayerUrl);
        }
        return tempLayerUrl;
    }

    //获取临时图层url
    private String getSqlTempLayer(String layerUrl, String sqlText,boolean showLabelBool) {
        String resultUrl = layerUrl;
        if (PlatformObjectUtils.isNotEmpty(sqlText)) {
            JSONArray jsonArray = getLayersRJson(layerUrl);
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONArray layers = jsonArray.getJSONObject(i).getJSONObject("subLayers").getJSONArray("layers");
                for(int j=0;j<layers.size();j++){
                    JSONObject layer = layers.getJSONObject(j);
                    layer.put("displayFilter",sqlText);
                    if(showLabelBool==false && layer.getString("ugcLayerType")=="THEME"){
                        if(layer.getJSONObject("theme").getString("type")=="LABEL"){//文字标签子图层
                            layer.put("visible",showLabelBool);
                        }
                    }
                }
            }
            String jsonStr = JSON.toJSONString(jsonArray);
            JSONObject resultObj = postTempLayersSet(layerUrl,jsonStr);
            String newResourceID = resultObj.getString("newResourceID");
            String newResourceLocation = resultObj.getString("newResourceLocation");
            if (PlatformObjectUtils.isNotEmpty(newResourceLocation)) {
                resultUrl = newResourceLocation.replace(".rjson","");
            }
        }
        return resultUrl;
    }

    private JSONArray getLayersRJson(String layerUrl) {
        try {
            String dataUrl = layerUrl + "/layers.rjson";
            try {
                dataUrl = URLDecoder.decode(dataUrl, "utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                return null;
            }
            dataUrl = dataUrl.replaceAll("%3A", ":").replaceAll("%2F", "/").replaceAll("\\+", "%20");
            //System.out.println(dataUrl);

            HttpHeaders headers = new HttpHeaders();
            headers.set("Content-Type", "application/json; charset=UTF-8");

            HttpEntity<JSONObject> entity = new HttpEntity<>(new JSONObject(), headers);
            ResponseEntity<String> exchange = restTemplate.exchange(dataUrl, HttpMethod.GET, entity, String.class);
            JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(exchange));
            JSONArray body = JSON.parseArray(jsonObject.getString("body"));
            if (body == null) {
                return null;
            }
            return body;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private JSONObject postTempLayersSet(String layerUrl, String jsonStr){
        JSONObject result = new JSONObject();
        String dataUrl = layerUrl + "/tempLayersSet.rjson";
        try {
            dataUrl = URLDecoder.decode(dataUrl, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }
        dataUrl = dataUrl.replaceAll("%3A", ":").replaceAll("%2F", "/").replaceAll("\\+", "%20");

        HttpHeaders headers = new HttpHeaders();
        headers.set("Content-Type", "application/json; charset=UTF-8");

        HttpEntity<String> entity = new HttpEntity<>(jsonStr, headers);
        ResponseEntity<String> exchange = restTemplate.exchange(dataUrl, HttpMethod.POST, entity, String.class);
        JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(exchange));
        JSONObject body = JSON.parseObject(jsonObject.getString("body"));
        if (body == null) {
            return null;
        }
        result = body;

        return result;
    }
    private List<Layerr> getLayerrs(String tjlx,Map<String,String> tempLayerUrlMap) {
        Properties configGroup = PropsHelper.loadProps("slw-config.properties");
        String url = configGroup.getProperty("supergraphRestTemplateUrl");
        List<Layerr> layerrs = null;
        if ("房屋破坏分布图".equals(tjlx)) {
            String url1 = tempLayerUrlMap.get("sys_house_destory");
            //图例
            List<String> strings1 = Arrays.asList("sys_house_destory@fxfzaqbz.2@@sys_house_destory@fxfzaqbz");
            Layerr layerr1 = new Layerr(url1 + "/map-fxfzaqbz/rest/maps/sys_house_destory@fxfzaqbz", strings1);

            List<String> strings15 = Arrays.asList("district_boundary_province@fxfzypg@@district_boundary_china@fxfzypg","district_boundary_city@fxfzypg@@district_boundary_china@fxfzypg","district_boundary_county@fxfzypg@@district_boundary_china@fxfzypg","district_boundary_province_text@fxfzypg@@district_boundary_china@fxfzypg","district_boundary_city_text@fxfzypg@@district_boundary_china@fxfzypg","district_boundary_county_text@fxfzypg@@district_boundary_china@fxfzypg");
            Layerr layerr15 = new Layerr(url + "/map-fxfzypg/rest/maps/district_boundary_china@fxfzypg",strings15);
           layerrs = Arrays.asList(layerr15,layerr1);
        }
        return layerrs;
    }
    private List<Layer> getLayer(String tjlx,Map<String,String> tempLayerUrlMap) {
        Properties configGroup = PropsHelper.loadProps("slw-config.properties");
        String url = configGroup.getProperty("supergraphRestTemplateUrl");
        List<Layer> layers = null;
        if ("房屋破坏分布图".equals(tjlx)) {
            //图层
            String url1 = tempLayerUrlMap.get("sys_house_destory");
          //  String url1 = url + "/map-fxfzaqbz/rest/maps/sys_house_destory@fxfzaqbz";
            Layer layer1 = new Layer("TILE","房屋破坏分布图",url1);
            String url15 = url + "/map-fxfzypg/rest/maps/district_boundary_china@fxfzypg";
            Layer layer15 = new Layer("TILE","中国行政区划图", url15);
            layers = Arrays.asList(layer15,layer1);
        }
        return layers;
    }
}
